<template>
  <context-menu :menu="[{ label: '清屏' }, { label: '不感兴趣' }, { label: '意见反馈' }, { label: '进入详情页' }, { label: '敬请期待' }]"
    @select="handleSelect">
    <div class="waterfall" ref="waterfall">
      <waterfall-box v-for="(item, index) in videoList" :key="index" :Videokey="index" :VideoURL="item.video_url"
        :coverURL="item.cover_url" :VideoDate="item.video_date" :VideoTitle="item.video_title"
        :VideoAuthor="item.author_name" ref="waterfallBox" @isReady=addReadyVideoNum></waterfall-box>
    </div>

    <!-- 添加分页组件 -->
    <div class="pagination-container">
      <el-config-provider :locale="zhCn">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
          :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" background />
      </el-config-provider>
    </div>
  </context-menu>
</template>

<script>
import WaterfallBox from '@/components/WaterfallBox.vue'
import ContextMenu from '@/components/contextMenu/index.vue'
import api from '@/api/axios.js'
import { ElConfigProvider } from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'

export default {
  components: { WaterfallBox, ContextMenu, ElConfigProvider },
  computed: {
    videoList: {
      get() { return this.$store.state.videoFunctionList.videoInfoList },
      set(val) { this.$store.commit('videoFunctionList/initVideoListInfo', val) }
    }
  },
  data() {
    return {
      imgWidth: 260,
      timerId: null,
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页显示数量
      total: 10,
      zhCn: zhCn
    }
  },
  mounted() {
    setTimeout(() => {
      this.getVideo({ page: this.currentPage, page_size: this.pageSize, searchContent: this.$route.query.search })
    }, 100)
    window.addEventListener('resize', this.antiShake)
  },
  methods: {
    handleSelect(val) {
      this.$message.open({
        tittle: val.label,
        type: 'success',
        duration: 1000,
        center: true
      })
    },
    layout() {
      let _this = this
      function getinfo() {
        let waterfallWidth = _this.$refs.waterfall.offsetWidth;
        let column = Math.floor(waterfallWidth / _this.imgWidth);
        let gapCount = column - 1 === 0 ? 1 : column - 1;
        let freeSpace = waterfallWidth - _this.imgWidth * column;
        let gap = freeSpace / gapCount;
        // 设置水平方向最小缝隙
        if (gap < 15) {
          gap = 15
          column--
        }
        return {
          gap: gap,
          column: column,
        };
      }
      let info = getinfo();
      let nextTop = new Array(info.column);
      nextTop.fill(0);
      // 求一维数组的最小值
      function getMinTop(nextTop) {
        let min = nextTop[0], index = 0;
        for (let i = 0; i < nextTop.length; i++) {
          if (nextTop[i] < min) {
            min = nextTop[i];
            index = i;
          }
        }
        return {
          min: min,
          index: index,
        };
      }
      // 求一维数组的最大值
      function getMaxTop(nextTop) {
        let max = nextTop[0], index = 0;
        for (let i = 0; i < nextTop.length; i++) {
          if (nextTop[i] > max) {
            max = nextTop[i];
            index = i;
          }
        }
        return {
          max: max,
          index: index,
        };
      }
      // 设置每个视频的位置
      for (let i = 0; i < _this.$refs.waterfall.children.length; i++) {
        const video = document.querySelector(`.waterfall .waterfallBox-border:nth-child(${i + 1})`)
        let minTop = getMinTop(nextTop)
        video.style.left = `${minTop.index * (_this.imgWidth + info.gap)}px`
        // 设置垂直方向的最小缝隙
        let minTopGap = info.gap / 2
        if (minTopGap < 20) minTopGap = 20
        // 第一行的不加垂直方向的缝隙
        if (i < info.column) {
          video.style.top = `${minTop.min}px`
          // 更新数组
          nextTop[minTop.index] = nextTop[minTop.index] + video.offsetHeight
        } else {
          video.style.top = `${minTop.min + minTopGap}px`
          nextTop[minTop.index] = nextTop[minTop.index] + video.offsetHeight + minTopGap
        }
        let maxTop = getMaxTop(nextTop)
        _this.$refs.waterfall.style.height = maxTop.max + 'px'
      }
    },
    // 防抖
    antiShake() {
      if (this.timerId) clearTimeout(this.timerId)
      this.timerId = setTimeout(this.layout, 300)
    },
    // 子组件加载好通知
    addReadyVideoNum() {
      this.antiShake()
    },
    // 实现懒加载
    createLazy() {
      const videorefs = this.$refs.waterfallBox
      const observer = new IntersectionObserver((entries) => {
        for (const entry of entries) {
          if (entry.isIntersecting) {
            for (const videoref of videorefs) {
              if (videoref.$el === entry.target) {
                videoref.videoReady()
                observer.unobserve(entry.target)
              }
            }
          }
        }
      })
      for (const videoref of videorefs) {
        observer.observe(videoref.$el)
      }
    },
    // 处理每页显示数量变化
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1 // 重置到第一页
      this.getVideo({ page: this.currentPage, page_size: this.pageSize })
    },
    // 处理页码变化
    handleCurrentChange(val) {
      this.currentPage = val
      this.getVideo({ page: val, page_size: this.pageSize })
    },
    getVideo(data) {
      api.getUserVideos(data).then((response) => {
        console.log(response);
        if (response.data.code === '200') {
          this.videoList = response.data.data.list
          this.currentPage = response.data.data.pagination.current
          this.pageSize = response.data.data.pagination.page_size
          this.total = response.data.data.pagination.total
        }
      }).then(() => {
        this.layout()
        this.createLazy()
      }).catch(function (error) {
        // 请求失败处理
        console.log(error);
      })
    }
  },
  destroyed() {
    // 移除监听事件
    window.removeEventListener('resize', this.antiShake)
  }
}
</script>

<style scoped>
.waterfall {
  position: relative;
  width: calc(100% - 60px);
  height: 100%;
  margin: 0 auto;
}

/* 添加分页容器样式 */
.pagination-container {
  position: fixed;
  bottom: 20px;
  right: 20px;
  padding: 15px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

/* 自定义分页组件样式 */
:deep(.el-pagination) {
  --el-pagination-hover-color: #409eff;
  --el-pagination-button-color: #303133;
  --el-pagination-button-bg-color: #fff;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #409eff;
}

:deep(.el-pagination.is-background .el-pager li) {
  margin: 0 4px;
}
</style>